/*=====================================================================
  This file is part of a Microsoft SQL Server Shared Source Application.
  Copyright (C) Microsoft Corporation.  All rights reserved.
 
THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
======================================================= */

using System;
using System.ComponentModel;
using System.Data;
using System.Xml.Serialization;
using System.Diagnostics;
using Microsoft.AnalysisServices.AdomdClient;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.SqlServer.BI.ASLoadSim
{
    /// <summary>
    /// Connect to an AS instance via ADOMD .NET provider
    /// Run specified query
    /// </summary>
    public class ASAdoMdNetConnection
    {
        private AdomdConnection m_conn;
        private string m_server;
        private string m_database;        

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="server"></param>
        /// <param name="db"></param>
        public ASAdoMdNetConnection(string server, string db)
        {
            m_server = server;
            m_database = db;
            m_conn = null;
        }

        /// <summary>
        /// Have we established the connection already?
        /// </summary>
        public bool IsConnected()
        {
            if (m_conn != null)
            {
                return (m_conn.State == ConnectionState.Open) ? true : false;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Connect to the server and database
        /// </summary>
        public void Connect(TestContext context)
        {
            try
            {
                if (m_conn != null && IsConnected())
                    throw new Exception("Connection has already been established.");

                string connStr = String.Format(
                                "Provider=MSOLAP;Data Source={0};Initial Catalog={1};",
                                m_server,
                                m_database);

                m_conn = new AdomdConnection(connStr);

                context.BeginTimer("TTC");
                m_conn.Open();
                context.EndTimer("TTC");
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// Release connection
        /// </summary>
        public void Disconnect()
        {
            if ((m_conn != null) && (IsConnected()))
            {
                m_conn.Close();
                m_conn.Dispose();
                m_conn = null;
            }
        }

        /// <summary>
        /// Submit query
        /// </summary>
        public void SendQuery(TestContext context, string query, string queryComment)
        {
            try
            {
                AdomdCommand cmd = null;
                CellSet cells = null;

                cmd = m_conn.CreateCommand();
                cmd.CommandText = query;
                cmd.CommandTimeout = 0;

                // Do not pass the entire query text to Timer
                // It is too long.
                // Pass only the query comment to Timer
                context.BeginTimer("TTFB: " + queryComment);
                context.BeginTimer("TTLB: " + queryComment);
                object executionObj = cmd.Execute();
                context.EndTimer("TTFB: " + queryComment);

                int m_cellsReturned;
                if (executionObj != null && executionObj.GetType() == typeof(CellSet))
                {
                    cells = (CellSet)executionObj;

                    m_cellsReturned = cells.Cells.Count;

                    foreach (Cell cell in cells.Cells)
                    {
                        string cellValue = cell.FormattedValue;

                    }
                }
                else
                {
                    cells = null;
                    m_cellsReturned = -1;
                }
                context.EndTimer("TTLB: " + queryComment);

                cmd.Dispose();
                cmd = null;
                cells = null;
            }
            catch (Exception e)
            {
                throw e;
            }
        }       
    }
}
